package com.example.gif.utils;

import com.madgag.gif.fmsware.AnimatedGifEncoder;
import org.springframework.core.io.ByteArrayResource;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;


/**
 * @author:YangHaoZhong
 * @time:2024/4/8
 */
public class ImageUtils {
//    public static void main(String[] args) {
//        try {
//            URL url = new URL("https://orderplus-cloud.aopcdn.com/orderPlus/b0cb0b9d2a214d6e96c825e5447c16e5.jpg");
//            BufferedImage var2 = getBufferedImage(url);
//        } catch (Exception var3) {
//            var3.printStackTrace();
//        }
//
//    }

    /**
     * 生成Gif图
     *
     * @param delay
     * @param bufferedImageArrayList
     * @param width
     * @param height
     * @return
     * @throws FileNotFoundException
     */
    public static ByteArrayResource getAnimatedGifEncoder(Integer delay, ArrayList<BufferedImage> bufferedImageArrayList, int width, int height) throws FileNotFoundException {
        AnimatedGifEncoder e = new AnimatedGifEncoder();
        e.setSize(width, height);
//        e.start(new FileOutputStream("test_gif.gif"));
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        e.start(byteArrayOutputStream);
        e.setDelay(delay);
        e.setRepeat(0);
        bufferedImageArrayList.forEach((bufferedImage) -> {
            e.addFrame(bufferedImage);
        });
        e.finish();
        ByteArrayResource byteArrayResource = new ByteArrayResource(byteArrayOutputStream.toByteArray());
        return byteArrayResource;
    }

    /**
     * 传入URL生成 BufferedImage
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static BufferedImage getBufferedImage(URL url) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(3000);
        InputStream inStream = conn.getInputStream();
        BufferedImage bufferedImage = bufferedImage(inStream);
        inStream.close();
        return bufferedImage;
    }

    /**
     * 读取字节流生成BufferedImage
     *
     * @param inStream
     * @return
     * @throws Exception
     */
    public static BufferedImage bufferedImage(InputStream inStream) throws Exception {
        BufferedImage read = ImageIO.read(inStream);
        inStream.close();
        return read;
    }

    /**
     * byte[]转BufferImage
     *
     * @param imgBytes
     * @return
     */
    public static BufferedImage bytes2bufImg(byte[] imgBytes) {
        BufferedImage tagImg = null;
        try {
            tagImg = ImageIO.read(new ByteArrayInputStream(imgBytes));
            return tagImg;
        } catch (IOException e) {
            throw new RuntimeException("bugImg写入失败:" + e.getMessage(), e);
        }
    }
}

